import { h, Component } from 'preact';
import { connect } from 'preact-redux';
import DockBar from '~/components/DockBar';
import HeaderBar from '~/components/HeaderBar';
import ScrollLoading from '~/components/ScrollLoading';
import Modal from '~/components/Modal';
import Loading from '~/components/Loading';
import { VLimit } from '~/utils/validate';
import { myGroups, createGroup, upImage } from '~/api/groups';
import history from '~/core/history';
import s from './Organization.scss';

class Organization extends Component {

	constructor(props){
		super(props);
		this.state = {
			list: [],
			showModal: false,
			visible: false,
			hide: false,
			dialogData: '',
			createGroupModal: false,
			success: false,
			successlist: {},
			nextpage: 0,
			currentpage: 1,
			cookId: this.props.user.id || null,
			imageUrl: null,
			isImage: null
		};
	}

	componentWillMount() {
		if (this.props.user.id) {
			this.getMyGroups(this.props.user.id, 0, 10);
		}
	}

	componentWillReceiveProps(nextProps) {
		if (nextProps.user !== this.props.user) {
			this.setState({
				cookId: nextProps.user.id
			});
			this.getMyGroups(this.state.cookId, 0, 10);
		}
	}

	getMyGroups = (cookId, page, size) => {
		Loading.show();
		myGroups(cookId, page, size).then(res => {
			if (res.length > 0) {
				this.setState({
					list: this.state.list.concat(res),
					nextpage: this.state.nextpage + 1
				});
			}

			Loading.hide();
		}).catch(err => {
			Loading.hide();
			this.showDialog({
				dialogTitle: '对不起',
				dialogContent: err.message ? err.message : '系统繁忙, 请稍后重试！'
			});
		});
	}

	handleAction = () => new Promise((resolve) => {
		this.getMyGroups(this.state.cookId, this.state.nextpage, 10);
		resolve();
	});

	handleEnter = (id) => () => {
		history.push(`/orgd?id=${id}`);
	}

	// 创建帮派
	createGroup = () => {
		this.setState({
			visible: true,
			createGroupModal: true,
			isImage: false
		});
	}

	handlerValidate = (data) => {
		if (!data.groupName) {
			this.showDialog({
				dialogTitle: '对不起',
				dialogContent: '帮派名不能为空！'
			});
			return false;
		}
		if (data.groupName.length <= 2 || data.groupName.length > 20) {
			this.showDialog({
				dialogTitle: '对不起',
				dialogContent: '帮派名要大于2个字符且不超过20个字符,请重新输入'
			});
			return false;
		}
		return true;
	}

	// 提交帮派信息
	handerCreateGroup = () => {
		this.setState({ createGroupModal: true });
		const sc = {};
		sc.groupName = this.groupName.value;

		if (!this.handlerValidate(sc)) {
			return false;
		}
		Loading.show();
		createGroup({
			groupName: this.groupName.value,
			groupLogo: this.state.imageUrl,
			masterId: this.state.cookId,
			passwd: '1234'
		}).then((res) => {
			Loading.hide();
			this.setState({
				success: true,
				createGroupModal: false,
				visible: false
			});
			this.showDialog({
				dialogTitle: '恭喜！',
				dialogContent: '创建帮派成功！'
			});
			this.groupName.value = '';
			this.setState({
				list: [],
				nextpage: 0
			});
			this.getMyGroups(this.state.cookId, 0, 10);
		}).catch(err => {
			Loading.hide();
			this.groupName.value = '';
			this.showDialog({
				dialogTitle: '对不起',
				dialogContent: err.message ? err.message : '系统繁忙, 请稍后重试！'
			});
		});
	}

	showDialog = (dialogData) => {
		this.setState(
			{
				visible: false,
				hide: true,
				dialogData
			}
    );
	}

	// 关闭创建帮派弹窗
	handerCloseDialog = () => {
		this.setState({
			visible: false
		});
	}

	// 关闭提示弹窗
	closeDialog = () => {
		if (this.state.createGroupModal) {
			this.setState({
				visible: true,
				hide: false,
				createGroupModal: false
			});
		} else {
			this.setState({ hide: false });
		}
	}

	upLoadImage = () => {
		window.wx.ready(
			() => {
				window.wx.chooseImage({
					count: 1, // 默认9
					sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success: (res) => {
						const localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
						window.wx.uploadImage({
							localId: localIds[0], // 需要上传的图片的本地ID，由chooseImage接口获得
							isShowProgressTips: 1, // 默认为1，显示进度提示
							success: (res) => {
								const serverId = res.serverId; // 返回图片的服务器端ID
								Loading.show();
								upImage({
									mediaId: serverId,
									isMaterial: 0
								}).then((data) => {
									this.setState({
										imageUrl: data,
										isImage: true
									});
									Loading.hide();
								}).catch(err => {
									Loading.hide();
									this.showDialog({
										dialogTitle: '对不起',
										dialogContent: err.message ? err.message : '系统繁忙, 请稍后重试！'
									});
								});
							}
						});
					}
				});
			}
		);
	}

	render() {
		const { list, success, successlist, imageUrl, isImage } = this.state;
		return (
			<div className={s.root}>
				<HeaderBar
					setTitle="帮派"
					// goBack
					// Next={{icon: 'icon-add'}}
				><span className={`icon-add white font-biggest pdl1 pdr1 ${s.add}`} onClick={this.createGroup}></span></HeaderBar>
				<div className={s.listwarp}>
					<ScrollLoading
						handleAction={this.handleAction}
						totalsize={10000}
						currentpage={this.state.currentpage}
						pagesize={10}
						backToTop
						setId={'lalala'}
					>
						<ul className={`${s.list} nls`} >
							{
								list.map((item, i) => (
								<li className="clearfix" key={i} onClick={this.handleEnter(item.id)}>
									<div className="w2-5 fl">
										<img src={item.groupLogo?`${item.groupLogo}?x-oss-process=image/resize,m_fill,h_200,w_200`:require('./face.jpg')} alt=""/>
									</div>
									<div className="w7-5">
										<h3 className="txt_cut font">{item.groupName}</h3>
										<p className="txt_cut gray font-small">({item.groupMemberSize}人)</p>
									</div>
								</li>
								))
							}
						</ul>
					</ScrollLoading>
				</div>
				<DockBar current={3} />
				<Modal
					contentLabel="Modal"
					isOpen={this.state.visible}
					onRequestClose={this.handleHideCard}
					shouldCloseOnOverlayClick={true}
				>
					<div className="pd1 clearfix">
						<h3 className={`al-c pdt1 orange-dark pdb1 font-bigger`}>创建帮派</h3>
						<div className={s.pic}>
							{
								isImage ? <img src={imageUrl} className="ww" /> :
								<div onClick={this.upLoadImage}>
									<span className="icon-add" />
									<p>上传图片</p>
								</div>
							}
						</div>
						<div className="pdb2">
							<input type="text" placeholder="帮派名" ref={ref => (this.groupName = ref)} />
						</div>
						<div
							onClick={this.handerCreateGroup}
							className="fl w4-8 al-c btn"
						>确定</div>
						<div
							onClick={this.handerCloseDialog}
							className="fr w4-8 btnb"
						>取消</div>
					</div>
				</Modal>
				<Modal
					contentLabel="Modal"
					isOpen={this.state.hide}
					onRequestClose={this.handleHideCard}
					shouldCloseOnOverlayClick={true}
				>
				<div className="pd1 clearfix">
					<h3 className={`al-c pdt1 orange-dark font-bigger`}>{this.state.dialogData.dialogTitle}</h3>
					<p className="pdt1 pdb2 al-c">{this.state.dialogData.dialogContent}</p>
					<div
						onClick={this.closeDialog}
						className="center w6 al-c btn"
					>确定</div>
				</div>
				</Modal>
			</div>
		);
	}
}

function mapStateToProps(state) {
	return {
		user: state.user
	};
}
export default connect(mapStateToProps)(Organization);
